package com.gombe.credit.app.ui.dialog

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.gombe.credit.app.GombeCreditApp
import com.gombe.credit.app.R
import com.gombe.credit.app.base.app.GombeCreditActivityStackManager
import com.gombe.credit.app.common.CommonDialog
import com.gombe.credit.app.configs.GombeCreditApiPath
import com.gombe.credit.app.configs.GombeCreditApiUrl
import com.gombe.credit.app.configs.GombeCreditApiUrl.addCommonParams
import com.gombe.credit.app.configs.GombeCreditConfigs
import com.gombe.credit.app.databinding.DialogGombeCreditCustomerBinding
import com.gombe.credit.app.event.GombeCreditEventPointHelper
import com.gombe.credit.app.event.GombeCreditEventPointType
import com.gombe.credit.app.request.IHttpCallback
import com.gombe.credit.app.ui.activity.ActGombeCreditUserAdviceType
import com.gombe.credit.app.ui.adapter.AdapterGombeCreditCustomer
import com.gombe.credit.app.utils.GombeCreditDensityUtil
import com.gombe.credit.app.utils.helper.GombeCreditConfigsHelper
import com.gombe.credit.app.utils.shared.GombeCreditSharedHelper
import com.gombe.credit.app.utils.shared.GombeCreditSharedKey
import com.gombe.credit.lib.adapter.GombeCreditOnItemChildClickListener
import org.json.JSONObject

/**
 * GombeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/15 10:29
 * @Annotation：联系客服Dialog
 */
class DialogGombeCreditCustomer(context: Context) : CommonDialog(context) {
    lateinit var binding: DialogGombeCreditCustomerBinding
    private var callback: IDialogCallback? = null
    //事件备注
    private var eventRemark = ""
    //产品名称
    private var pName = GombeCreditConfigs.GOMBECREDIT_APPNAME
    //产品Token
    private var pToken = GombeCreditSharedHelper.takeGombeCreditSharedString(GombeCreditSharedKey.GOMBECREDIT_TOKEN)
    //客服联系方式列表
    private var customerAdapter: AdapterGombeCreditCustomer? = null

    override fun initGombeCreditWindow() {
        val params = window?.attributes
        params?.width = GombeCreditApp.app.getPhoneWidth() - GombeCreditDensityUtil.dp2px(32f)
        params?.height = WindowManager.LayoutParams.WRAP_CONTENT
        window?.attributes = params
        window?.setWindowAnimations(R.style.dialog_slide_anim) //修改动画样式
        window?.setGravity(Gravity.CENTER)
    }

    override fun takeGombeCreditRootView(): View {
        binding = DialogGombeCreditCustomerBinding.inflate(LayoutInflater.from(context))
        return binding.root
    }

    override fun initGombeCreditView() {
        initGombeCreditCustomerListView()
    }

    override fun initGombeCreditListener() {
        setOnClickListener(binding.imgCustomerClose)
        setOnClickListener(binding.textCustomerFeedback)
    }

    override fun takeGombeCreditData() {
        val isLogin = GombeCreditSharedHelper.takeGombeCreditSharedBoolean(GombeCreditSharedKey.GOMBECREDIT_LOGIN)
        if (isLogin){
            binding.textCustomerFeedback.visibility = View.VISIBLE
        } else {
            binding.textCustomerFeedback.visibility = View.GONE
        }

        //主产品
        if (this.pName == GombeCreditConfigs.GOMBECREDIT_APPNAME){
            val commonInfo = GombeCreditSharedHelper.takeGombeCreditSharedString(GombeCreditSharedKey.GOMBECREDIT_COMMON)
            if (commonInfo.isEmpty()){
                loadGombeCreditCustomerContactListAction()
                return
            }
            val data = JSONObject(commonInfo)
            setGombeCreditCustomerContactData(data)
        } else {
            loadGombeCreditCustomerContactListAction()
        }
    }

    override fun onGombeCreditViewClick(v: View?) {
        dismiss()
        when(v?.id){
            R.id.textCustomerFeedback -> {
                onGombeCreditCustomerFeedbackAction()
            }
        }
    }

    /**
     * 事件备注
     */
    fun setGombeCreditCustomerEventRemark(remark: String): DialogGombeCreditCustomer {
        this.eventRemark = remark
        return this
    }

    /**
     * 对应的产品名称
     */
    fun setGombeCreditCustomerProductName(name: String): DialogGombeCreditCustomer {
        if (name.isNotEmpty()){
            this.pName = name
        }
        return this
    }

    /**
     * 对应的产品Token
     */
    fun setGombeCreditCustomerProductToken(token: String): DialogGombeCreditCustomer {
        if (pToken.isNotEmpty()){
            this.pToken = token
        }
        return this
    }

    /**
     * 设置监听回调
     */
    fun setGombeCreditCustomerClickCallback(callback: IDialogCallback): DialogGombeCreditCustomer {
        this.callback = callback
        return this
    }

    fun setGombeCreditCustomerCancelable(flag: Boolean): DialogGombeCreditCustomer {
        setCancelable(flag)
        return this
    }

    fun setGombeCreditCustomerCanceledOnTouchOutside(flag: Boolean): DialogGombeCreditCustomer {
        setCanceledOnTouchOutside(flag)
        return this
    }

    /**
     * 初始化Tab列表
     */
    private fun initGombeCreditCustomerListView() {
        binding.textCustomerWorkTime.visibility = View.GONE
        binding.customerListView.visibility = View.GONE
        binding.customerListView.layoutManager = LinearLayoutManager(context)
        customerAdapter = AdapterGombeCreditCustomer(binding.customerListView)
        binding.customerListView.adapter = customerAdapter
        binding.customerListView.itemAnimator = DefaultItemAnimator()
        customerAdapter?.setOnItemChildClickListener(GombeCreditOnItemChildClickListener { _, childView, position ->
            if (childView.id == R.id.textCustomerFun) {
                customerAdapter?.let {
                    val item = it.getItem(position)
                    when (item.optString("type")) {
                        "MOBILE" -> {//电话
                            callback?.onGombeCreditCallPhoneClick(item.optString("value"))
                            onGombeCreditCustomerMobileCallAction(item.optString("value"))
                        }

                        else -> {//邮箱
                            callback?.onGombeCreditCopyEmailClick(item.optString("value"))
                        }
                    }
                }
            }
        })
    }

    /**
     * 获取联系方式列表
     */
    private fun loadGombeCreditCustomerContactListAction(){
        val httpUrl = GombeCreditApiUrl.takeRequestUrl()
        val params = JSONObject().addCommonParams().apply {
            put("path", GombeCreditApiPath.GOMBECREDIT_PATH.GOMBECREDIT_API_APP_INFO_PATH)
            put("product",pName)
            put("token",pToken)
        }

        doPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                //保存所有数据
                if (obj != null) {
                    setGombeCreditCustomerContactData(obj)
                }
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
            }
        })
    }

    /**
     * 获取联系方式列表
     */
    @SuppressLint("SetTextI18n")
    private fun setGombeCreditCustomerContactData(data: JSONObject){
        binding.textCustomerWorkTime.visibility = View.VISIBLE
        binding.customerListView.visibility = View.VISIBLE
        val contactList = arrayListOf<JSONObject>()
        val customize = data.optJSONObject("customize")
        customize?.let {
            if (it.optString("mobile","").isNotEmpty()){
                val mobileList = it.optString("mobile").split(",")
                for (i in mobileList.indices){
                    val obj = JSONObject()
                    obj.put("type","MOBILE")
                    obj.put("value", mobileList[i])
                    contactList.add(obj)
                }
            }

            if (it.optString("email","").isNotEmpty()){
                val emailList = it.optString("email").split(",")
                for (i in emailList.indices){
                    val obj = JSONObject()
                    obj.put("type","EMAIL")
                    obj.put("value", emailList[i])
                    contactList.add(obj)
                }
            }
        }
        customerAdapter?.data = contactList

        //工作时间
        //客服配置里没有配置工作时间，取主产品的工作时间展示
        var workTime = "Monday to Sunday,9:00am to 6:30pm"
        customize?.let {
            val customData = it.optJSONObject("customData")
            if (customData != null){
                if (!customData.has("workDate") || !customData.has("workTime")){
                    val commonCustomData = GombeCreditConfigsHelper.takeGombeCreditCustomData()
                    if (commonCustomData != null) {
                        customData.put("workDate",commonCustomData.optString("workDate"))
                        customData.put("workTime",commonCustomData.optString("workTime"))
                    }
                }
                workTime = "${customData.optString("workDate")},${customData.optString("workTime")}"
            }
        }

        val showWorkTime = String.format(getString(R.string.gombe_credit_string_customer_dialog_time), workTime)
        val workTimeSpannable = SpannableString(showWorkTime)
        val startIndex = showWorkTime.indexOf(workTime)
        workTimeSpannable.setSpan(ForegroundColorSpan(getColor(R.color.gombe_credit_ff1d1e20)), startIndex, startIndex + workTime.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        binding.textCustomerWorkTime.text = workTimeSpannable
    }

    /**
     * 拨号
     */
    private fun onGombeCreditCustomerMobileCallAction(mobile: String){
        GombeCreditEventPointHelper.addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.CUSTOMER_DIAL, "Mobile ：$mobile")
        val callIntent = Intent(Intent.ACTION_DIAL)
        callIntent.setData(Uri.parse("tel:$mobile"))
        context.startActivity(callIntent)
    }


    /**
     * feedback
     */
    private fun onGombeCreditCustomerFeedbackAction(){
        //当前栈顶是 意见反馈类型
        if (GombeCreditActivityStackManager.isCurrentActivity(ActGombeCreditUserAdviceType::class.java)){
            return
        }
        GombeCreditEventPointHelper.addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.CUSTOMER_FEEDBACK)
        val intent = Intent(context, ActGombeCreditUserAdviceType::class.java)
        context.startActivity(intent)
    }

    interface IDialogCallback {
        //拨号
        fun onGombeCreditCallPhoneClick(phoneNumber: String)
        //Copy
        fun onGombeCreditCopyEmailClick(email: String)
        //feedback
        fun onGombeCreditFeedbackClick()
    }

    override fun onStart() {
        super.onStart()
        GombeCreditEventPointHelper.addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_DIALOG.CUSTOMER_SHOW,eventRemark)
    }

    override fun dismiss() {
        super.dismiss()
        GombeCreditEventPointHelper.addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_DIALOG.CUSTOMER_DISMISS,eventRemark)
    }
}